package com.hanj.spring;

import com.hanj.dao.impl.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author hanj.cn@outlook.com
 */
public class JDKProxyFactory implements InvocationHandler {

    //要代理的原始对象
    private Object target;

    /**
     * 创建动态代理
     *
     * @param target 要代理的原始对象
     * @return 代理对象
     */
    public Object createProxyInstance(Object target) {

        this.target = target;
        return Proxy.newProxyInstance(
                this.target.getClass().getClassLoader(),
                this.target.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        Object result = null;
        UserDaoImpl bean = (UserDaoImpl) this.target;
        if (bean != null) {
            // 前置通知
            doBefore();
            try {
                result = method.invoke(target, args);
                // 后置通知
                doAfter();
            } catch (Exception e) {
                // 例外通知
                doException();
            } finally {
                // 最终通知
                doFinally();
            }
        }
        return result;
    }

    private void doBefore() {

        System.out.println("我是前置通知");
    }

    private void doAfter() {

        System.out.println("我是后置通知");
    }

    private void doException() {

        System.out.println("我是例外通知");
    }

    private void doFinally() {

        System.out.println("我是最终通知");
    }

}
